package com.shadowlight.hero_story.pojo;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.ArrayList;
import java.util.List;


/**
 * @Description 简单的做一个信道hash-用户库，记录用户的实时状态
 * @Author cz
 * @Date 2022/2/28
 */
public final class UserRepository {

    private static final UserRepository USER_REPOSITORY = new UserRepository();
    private static final Cache<Integer, User> ID_USER_REPOSITORY = Caffeine.newBuilder()
//            .expireAfterWrite(10, TimeUnit.MINUTES)     //过期时间，后面调整
            .maximumSize(1000)      //最大连接个数
            .build();

    private UserRepository() {
    }

    public static UserRepository getInstance() {
        return USER_REPOSITORY;
    }

    public void save(User user) {
        if (user == null) return;
        ID_USER_REPOSITORY.put(user.getId(), user);
    }


    public User getUserById(int id) {
        return ID_USER_REPOSITORY.getIfPresent(id);
    }


    public List<User> getAll() {
        return new ArrayList<>(ID_USER_REPOSITORY.asMap().values());
    }


    public void removeUserById(int id) {
        ID_USER_REPOSITORY.invalidate(id);
    }
}
